package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.UserMedPlanMedEntity;

public class UserMedPlanMedDAO {
	public boolean insert(Connection conn, List<UserMedPlanMedEntity> list) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn
				.prepareStatement("insert into user_med_plan_med(time,med_id,med_plan_id,count) values(?,?,?,?)");
		for (UserMedPlanMedEntity eMedEntity : list) {
			ps.setString(1, eMedEntity.getTime());
			ps.setInt(2, eMedEntity.getMed_id());
			ps.setInt(3, eMedEntity.getMed_plan_id());
			ps.setInt(4, eMedEntity.getCount());
			ps.addBatch();
		}
		if (ps.executeBatch().length > 0) {
			b = true;
		}
		return b;
	}

	public List<UserMedPlanMedEntity> listByPlanId(Connection conn, int med_plan_id) throws SQLException {
		List<UserMedPlanMedEntity> list = new LinkedList<UserMedPlanMedEntity>();
		PreparedStatement ps = conn.prepareStatement("select * from user_med_plan_med where med_plan_id=?");
		ps.setInt(1, med_plan_id);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			UserMedPlanMedEntity entity = fill(rs);
			list.add(entity);
		}
		return list;
	}

	private UserMedPlanMedEntity fill(ResultSet rs) throws SQLException {
		UserMedPlanMedEntity entity = new UserMedPlanMedEntity();
		entity.setId(rs.getInt("id"));
		entity.setCount(rs.getInt("count"));
		entity.setMed_id(rs.getInt("med_id"));
		entity.setMed_plan_id(rs.getInt("med_plan_id"));
		entity.setTime(rs.getString("time"));
		return entity;
	}

	public boolean deleteByPlanId(Connection conn, int med_plan_id) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn.prepareStatement("delete from user_med_plan_med where med_plan_id=?");
		ps.setInt(1, med_plan_id);
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}

	public boolean set(Connection conn, List<UserMedPlanMedEntity> list, int med_plan_id) throws SQLException {
		deleteByPlanId(conn, med_plan_id);
		return insert(conn, list);
	}

}
